<?php
$tid = 0;
if (isset($argv[1]) && $argv[1] != '') {
    $tid = $argv[1];
}
if (isset($argv[2]) && $argv[2] != '') {
    $env = $argv[2];
}
if (isset($argv[3]) && $argv[3] != '') {
    $table = $argv[3];
}
define('ERROR_LEVEL', E_WARNING | E_ERROR | E_PARSE); 
define('DB_READ_LINK_TAG', '_admin');
include('/var/www/html/gutou/common/APPbase_cli.php');

class APP extends APPbase
{

    static $random = '';
    static $update_num = 0;
    static $insert_num = 0;
    static $delete_num = 0;
    static $query_num = 0;
    static $tid = 0;

    public static function runBefore() 
    {
        self::$cart_abled = false;
        self::$template_ebled = false;
    }

    public static function createDir($dirPath){
        if(!is_dir($dirPath)){
            try{
                return mkdir($dirPath,0755,true);
            }catch (\Exception $exception){
                return false;
            }
        }else{
            return true;
        }
    }


    public static function runFunc($tid = 0, $env='epet-local', $table)
    {
        //ini_set('memory_limit','-1');
        self::run();
        if (empty($tid)) {
            $tid = APP::get('tid');
        }
        if (empty($table)) {
            $table = APP::get('table');
        }
        if ($tid) {
            $starttime = time();
            $query = mod_plugin_remote::query2("SELECT * FROM {$table} WHERE tid='$tid' LIMIT 1");
            $akr = $query->fetch(PDO::FETCH_ASSOC);
            
            if (!$akr) {
                APP::edie('没有此执行任务tid');
            }
            $lock = "lock_status=1";
            mod_plugin_remote::query2("UPDATE {$table} SET runtime_beg='$starttime',runtime_start='$starttime', $lock WHERE tid='$tid'");
            $run_finished = true;
            $logs = '';
            /**
             * 执行定时业务逻辑
             */
            self::$tid = $tid;
            self::$random = Func::random(32);
            $start_time = microtime(true);
            $filecrons = ROOT_GT . '/framework/class/crons/' . $akr['file'];
            try {
                include_once($filecrons);
            } catch (Exception $e) {
                mod_plugin_alisls::put($e->getMessage() . ';[' . $e->getTraceAsString() . ']', 'gearman', "gearman");
            }
            $end_time = microtime(true) - $start_time;
            $end_time = round($end_time, 3);

            if($env == 'epet-product') {
                $global_monitor = [
                    'random' => self::$random,
                    'runtime' => $end_time,
                    'query_num' => self::$query_num,
                    'insert_num' => self::$insert_num,
                    'update_num' => self::$update_num,
                    'delete_num' => self::$delete_num,
                    'run_finished' => $run_finished,
                    'tid' => $tid,
                    'type' => 'global',
                    'addtime' => date('Y-m-d H:i:s', time())
                ];
                if (self::$query_num >= 400 || self::$insert_num >= 200 || self::$update_num >= 200 || self::$delete_num >= 200) {
                    mod_plugin_alisls::put('发生规定值报警tid:' . $tid . '--query:' . self::$query_num . '--insert:' . self::$insert_num . '--update:' . self::$update_num . '--delete:' . self::$delete_num, 'gearman', "gearman");
                }
                $logDir = '/www/logs/timertask-logtail';
                self::createDir($logDir);
                file_put_contents("{$logDir}/task_" . $tid . ".log", json_encode($global_monitor) . "\n", FILE_APPEND);
            }

            /**
             * 处理业务返回结果
             */
            $endtime = time();
            $logs .= '执行了' . ($endtime - $starttime) . '秒';
            $lastupdate = date('Y-m-d H:i:s', $endtime);
            if ($run_finished === true) {
                mod_plugin_remote::query2(
                        "UPDATE {$table} SET
                        lastupdate='{$lastupdate}',
                        mark='{$logs}',
                        runtimes=1,
                        lock_status=0
                        WHERE tid={$tid}"
                );

            } else if ($run_finished === false) {
                $logs .= '执行了' . ($endtime - $starttime) . '秒，等待继续执行..';
                mod_plugin_remote::query2("UPDATE {$table} SET
                        lastupdate='{$lastupdate}',
                        mark='{$logs}',
                        runtimes={$akr['runtimes']} + 1,
                        lock_status=0
                        WHERE tid={$tid}"
                );

            } else {
                $logs .= '执行了' . ($endtime - $starttime) . '秒';
                mod_plugin_remote::query2("UPDATE {$table}  SET
                    lastupdate='{$lastupdate}',
                    mark='{$logs}',
                    runtimes=1,
                    lock_status=0
                    WHERE tid={$tid}"
                );
            }
            echo $logs;
            return $logs;
        }
    }
}

APP::runFunc($tid, $env, $table);
